package com.yxx.web.controller.system;

import com.google.code.kaptcha.Producer;
import com.yxx.common.constant.CacheConstants;
import com.yxx.common.constant.Constants;
import com.yxx.common.core.redis.RedisCache;
import com.yxx.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;
import com.yxx.common.core.controller.BaseController;
import com.yxx.common.core.domain.AjaxResult;
import com.yxx.common.core.domain.model.RegisterBody;
import com.yxx.common.utils.StringUtils;
import com.yxx.framework.web.service.SysRegisterService;
import com.yxx.system.service.ISysConfigService;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;

/**
 * 注册验证
 */
@RestController
public class SysRegisterController extends BaseController
{
    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private JavaMailSenderImpl javaMailSender;

    @Autowired
    private RedisCache redisCache;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody user)
    {
        if (!configService.selectRegisterEnabled())
        {
            return error("当前系统没有开启注册功能！");
        }
        String msg = registerService.register(user);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }

    @GetMapping("/register")
    public AjaxResult register()
    {
        return success(configService.selectRegisterEnabled());
    }

    @GetMapping("/register/{email}")
    public AjaxResult email(@PathVariable String email)
    {
        MimeMessage message = javaMailSender.createMimeMessage();
        String code = captchaProducer.createText();
        AjaxResult ajax = AjaxResult.success();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(email);
            helper.setFrom("1303490776@qq.com");
            helper.setSubject("注册验证码，有效期1分钟");
            helper.setText(code);
            javaMailSender.send(message);
            // 保存验证码信息
            String uuid = IdUtils.simpleUUID();
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
            redisCache.setCacheObject(verifyKey, code, 1, TimeUnit.MINUTES);
            ajax.put("uuid", uuid);
        } catch (Exception e) {
            logger.error("发送错误：", e);
            return error("发送错误：" + e.getMessage());
        }
        return ajax;
    }
}
